package com.example.mykotilin.room.persistence

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

/**
 * 注解表明数据库创建，用于创建数据库
 */
@Database(entities = [User::class],version = 1)
abstract class UserDatabase : RoomDatabase() {
    abstract fun  userDao(): UserDao

    //伴生对象
    companion object{
        @Volatile private var INSTANCE :UserDatabase?=null;
        //异步创建实例
        fun  getInstance(context:Context):UserDatabase =
            INSTANCE ?: synchronized(this){
            INSTANCE ?: buildDatabase(context).also {
                INSTANCE=it }
        }

        /**
         * 创建一个数据库对象实例
         */
        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext,
                UserDatabase::class.java,"Sample.db").build()
    }

}